<template>
  <div
    class="Detail_business"
    :class="permissionVerification('edit',detailType) ? 'business_bottom' : ''"
  >
    <PullRefresh
      class="kpInfo-detail detail"
      v-model="refreshing"
      @refresh="onRefresh"
    >
      <List
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :immediate-check="false"
        @load="onLoad"
      >
        <div>
          <div v-for="v in list" :key="v.id" class="info">
            <h4 class="flex justify-between pb-12px items-center">
              <div class="name">{{ v.name }} {{ v.positionStr }}</div>
              <div>
                <Button
                  v-if="permissionVerification('edit', detailType)"
                  @click="edit(v, (type = '编辑'))"
                  size="mini"
                  style="width: 64px; padding: 0; height: 25px"
                  ><div class="flex">
                    <img
                      src="../../../assets/business/icon_bj.png"
                      alt=""
                      width="14px"
                      height="14px"
                      class="mr-6px"
                    /><span>编辑</span>
                  </div></Button
                >
              </div>
            </h4>
            <div class="mt-12px">
              <span class="inline-block mr-4px">手机号：</span>
              <span style="color: #333333">{{ v.phone }}</span>
            </div>
            <div class="mt-12px">
              <span class="inline-block mr-4px">微信号：</span>
              <span style="color: #333333">{{ v.wechat }}</span>
            </div>
            <div class="mt-12px">
              <span class="inline-block mr-4px">座机号：</span>
              <span style="color: #333333">{{ v.landline }}</span>
            </div>
          </div>
        </div>
      </List>
    </PullRefresh>
    <div v-if="permissionVerification('edit', detailType)" class="add">
      <Button type="info" @click="edit(null, (type = '新增'))" block
        >新增KP</Button
      >
    </div>
    <ActionSheet
      v-model="editShow"
      :title="title"
      :closeable="false"
      class="safePadding my_form"
    >
      <van-form :show-error-message="false" :show-error="false" ref="form">
        <van-field
          v-model="editFrom.name"
          name="KP姓名/称呼"
          label="KP姓名"
          placeholder="KP姓名/称呼"
          :rules="[{ required: true, message: '请填写KP姓名/称呼' }]"
          :class="editFrom.name ? 'exist_value' : ''"
        />
        <van-field
          readonly
          clickable
          is-link
          name="area"
          :value="editFrom.positionStr"
          label="KP职位"
          placeholder="点击选择KP职位"
          @click="changePos"
          :rules="[{ required: true, message: '请KP职位' }]"
          :class="editFrom.positionStr ? 'exist_value' : ''"
        />

        <van-field
          v-model="editFrom.phone"
          name="手机号"
          label="手机号"
          placeholder="手机号、微信、座机至少填写一个"
          :class="editFrom.phone ? 'exist_value' : ''"
        />

        <van-field
          v-model="editFrom.wechat"
          name="微信号"
          label="微信号"
          placeholder="手机号、微信、座机至少填写一个"
          :class="editFrom.wechat ? 'exist_value' : ''"
        />
        <van-field
          v-model="editFrom.landline"
          name="座机号"
          label="座机号"
          placeholder="手机号、微信、座机至少填写一个"
          :class="editFrom.landline ? 'exist_value' : ''"
        />
        <PopupAction @confirm="editSubmit" @cancel="editShow = false" />
      </van-form>
    </ActionSheet>
    <van-popup
      round
      @close="close"
      v-model="showPos"
      position="bottom"
      class="safePadding stateInfo"
    >
      <h3 class="px-4 py-5">KP职位</h3>
      <van-picker
        ref="changePos"
        title="KP职位"
        :columns="PosData"
        :swipe-duration="100"
      />
      <PopupAction @confirm="confirmPos" @cancel="showPos = false" />
    </van-popup>
    <actionPopup
      ref="actionPopup"
      :content="actionP.content"
      :showButtons="actionP.showButtons"
      :confirmText="actionP.confirmText"
      :title="actionP.title"
      :backText="actionP.backText"
      @back="back"
    ></actionPopup>
  </div>
</template>

<script>
import {
  contractKp,
  businessDataStatus,
  editKP,
  addKP,
  kpCheck,
} from "@/services/business/HighSeas.js";
import {
  Button,
  PullRefresh,
  ActionSheet,
  Form,
  Field,
  Toast,
  Popup,
  Picker,
  List,
} from "vant";
import Bus from "@/config/evenrBus";
import actionPopup from "@/components/ll-action-popup";
import PopupAction from "@/views/business/components/popup_action.vue";
import { getLocationParam, permissionVerification } from "@/utils/tools";
export default {
  components: {
    Button,
    PullRefresh,
    ActionSheet,
    List,
    PopupAction,
    actionPopup,
    [Form.name]: Form,
    [Field.name]: Field,
    [Popup.name]: Popup,
    [Picker.name]: Picker,
  },
  props: {
    detailType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      actionP: {},
      editFrom: {},
      editShow: false,
      list: [],
      id: null,
      title: "",
      showPos: false,
      PosData: [],
      PosData1: [],
      loading: false,
      refreshing: false,
      finished: false,
      type: "",
      permission: "",
      permissionVerification: permissionVerification,
    };
  },

  methods: {
    change(val) {
      this.id = val;
      this.permission = getLocationParam("permission");
      this.getData();
    },
    back() {
      this.editShow = false;
    },
    close() {
      this.editShow = true;
      this.showPos = false;
    },
    //KP职位选择
    confirmPos() {
      this.showPos = false;
      let val = this.$refs.changePos.getValues()[0];
      this.PosData1.forEach((v) => {
        if (v.name == val) {
          this.editFrom.positionStr = val;
          this.editFrom.position = v.type;
        }
      });
    },
    changePos() {
      this.editShow = false;
      this.showPos = true;
      this.PosData = [];
      businessDataStatus({ type: "kp_position" })
        .then((res) => {
          this.PosData1 = res;
          res.forEach((v) => {
            this.PosData.push(v.name);
          });
        })
        .catch((e) => {
          Toast(e.errMessage || e.message);
        });
    },
    _validator() {
      const { phone, landline, wechat } = this.editFrom;
      const value = phone || landline || wechat;
      return !!value;
    },
    //编辑提交
    editSubmit() {
      this.$refs.form
        .validate()
        .then(() => {
          const { phone, landline, wechat } = this.editFrom;
          if (!phone && !landline && !wechat) {
            Toast("手机号、微信、座机至少填写一个");
            return;
          }
          if (phone) {
            if (!/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/.test(phone)) {
              Toast("请输入正确的手机号");
              return;
            }
          }
          if (landline) {
            if (
              !/0\d{2,3}-\d{7,8}|\(?0\d{2,3}[)-]?\d{7,8}|\(?0\d{2,3}[)-]*\d{7,8}/.test(
                landline
              )
            ) {
              Toast("请输入正确的座机号");
              return;
            }
          }
          console.log(this.editFrom);
          if (this.type === "编辑") {
            editKP({
              id: this.editFrom.kpId,
              businessOpportunityId: this.id,
              wechat: this.editFrom.wechat,
              landline: this.editFrom.landline,
              phone: this.editFrom.phone,
              position: this.editFrom.position,
              name: this.editFrom.name,
            })
              .then((res) => {
                console.log(res);
                this.editShow = false;
                this.getData();
              })
              .catch((e) => {
                Toast(e.message || e.errMessage);
                this.editShow = false;
              });
          } else if (this.type === "新增") {
            addKP({
              businessOpportunityId: this.id,
              wechat: this.editFrom.wechat,
              landline: this.editFrom.landline,
              phone: this.editFrom.phone,
              position: this.editFrom.position,
              name: this.editFrom.name,
            })
              .then((res) => {
                console.log(res);
                this.getData();
                this.editShow = false;
              })
              .catch((e) => {
                Toast(e.message || e.errMessage);
              });
          }
        })
        .catch((e) => {
          console.log(e);
          Toast({ message: e[0].message, position: "top" });
          // this.editShow = false;
        });
    },
    //编辑
    edit(val, type) {
      this.editFrom = {};
      if (type === "编辑") {
        kpCheck()
          .then((res) => {
            console.log(res);
            if (res && res.code) {
              Toast(res.message);
              return;
            } else {
              this.editFrom = { ...val };
              this.title = "编辑KP";
              this.type = "编辑";
              this.editShow = true;
            }
          })
          .catch((err) => {
            console.log(err);
            if (err.code === 1000) {
              this.actionP.title = "";
              this.actionP.content = err.errMessage || err.message;
              this.actionP.showButtons = "back";
              this.actionP.backText = "返回";
              this.$nextTick(() => {
                this.$refs.actionPopup.open(this.actionP);
              });
              return;
            } else {
              Toast(err.errMessage || err.message);
              return;
            }
          });
      } else if (type === "新增") {
        this.editShow = true;
        this.title = "新增KP";
        this.type = "新增";
      }
    },
    onLoad() {
      setTimeout(() => {
        if (this.refreshing) {
          this.refreshing = false;
        }
        this.loading = false;
        this.finished = true;
      }, 1000);
    },
    onRefresh() {
      this.finished = false;
      // this.loading = true;
      // this.onLoad();
      this.getData();
    },
    getData() {
      if (this.$store.state.business.businessId) {
        this.id = this.$store.state.business.businessId;
      } else {
        this.id = Number(this.$route.query.id);
      }
      this.loading = true;
      contractKp({ id: this.id })
        .then((res) => {
          this.loading = false;
          console.log(res);
          this.refreshing = false;
          this.loading = false;
          this.list = res;
        })
        .catch((e) => {
          Toast(e.message || e.errMessage);
          this.refreshing = false;
          this.loading = false;
        });
    },
  },
  beforeDestroy() {
    Bus.$off("Details");
  },
};
</script>

<style lang="less" scoped>
.Detail_business {
  height: calc(100vh - 90px);
  overflow: auto;
  padding-bottom: 10px;
  .safePadding {
    padding-bottom: calc(50px + env(safe-area-inset-bottom));
  }
  .van-action-sheet__header {
    text-align: left;
    line-height: normal;
    padding-top: 20px;
    padding-bottom: 12px;
    font-family: PingFangSC-Medium, PingFang SC;
    color: #333333;
    font-size: 16px;
    font-weight: 600;
    padding-left: 16px;
  }
  .add {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 98px;
    padding: 10px 14px 44px;
    background-color: #fff;
    .van-button {
      border-radius: 10px;
    }
  }

  .kpInfo-detail {
    .info {
      padding-top: 16px;
      margin: 10px;
      background-color: #fff;
      border-radius: 8px;
      color: #666;
      font-size: 13px;
      padding-bottom: 12px;
      & > div {
        margin-left: 12px;
      }
      h4 {
        padding-right: 12px;
        border-bottom: 1px solid #f5f5f5;
        .name {
          font-size: 16px;
          font-weight: 600;
          color: #333;
          display: flex;
          align-items: center;
          flex-grow: 1;
          &:before {
            content: "";
            border-left: 4px solid #1d6fe9;
            margin-right: 8px;
            height: 12px;
            display: block;
          }
        }
        .van-button--mini {
          border-radius: 16px;
          border: 1px solid #1d6fe9;
          background-color: rgba(29, 111, 233, 0.1);
          padding: 4px 10px;
          .van-icon-edit:before {
            color: #1d6fe9;
            margin-right: 7px;
          }
          .van-button__text {
            color: #1d6fe9;
            font-size: 12px;
          }
        }
      }
      .van-button--mini {
        border: none;
        .van-button__text {
          color: #1d6fe9;
          font-size: 14px;
        }
      }
    }
  }
}
.business_bottom {
  height: calc(100vh - 190px - env(safe-area-inset-bottom));
}
</style>
